package com.drawu.drawuspring.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.drawu.drawuspring.constants.BehaviorConstants;
import com.drawu.drawuspring.domain.DTO.CollectBehaviorDto;
import com.drawu.drawuspring.domain.po.CollectRecord;
import com.drawu.drawuspring.domain.po.Users;
import com.drawu.drawuspring.mapper.CollectRecordMapper;
import com.drawu.drawuspring.service.ICollectRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.drawu.drawuspring.utils.AppThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <p>
 * 收藏记录表 服务实现类
 * </p>
 *
 * @author hui
 * @since 2024-10-12
 */
@Service
@RequiredArgsConstructor
public class CollectRecordServiceImpl extends ServiceImpl<CollectRecordMapper, CollectRecord> implements ICollectRecordService {

    private  final StringRedisTemplate redisTemplate;

    /**
     * 保存收藏记录
     */
    @Override
    public void saveCollectRecord(CollectBehaviorDto dto) {
        CollectRecord record = new CollectRecord();
        Users user = AppThreadLocalUtil.getUser();
        record.setUserId(user.getId());
        record.setPostsId(dto.getPostsId());
        this.save(record);
    }

    /**
     * 删除收藏记录
     *
     */
    @Override
    public void deleteCollectRecord(CollectBehaviorDto dto) {
        QueryWrapper<CollectRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", String.valueOf(AppThreadLocalUtil.getUser().getId()))
               .eq("posts_id", dto.getPostsId());
        this.remove(wrapper);
    }

    /**
     * 获取用户收藏的帖子id列表
     *
     */
    @Override
    public Set<Integer> getCollectsRecordList(List<Integer> postIds) {
//判断用户是否登录
        Users user = AppThreadLocalUtil.getUser();
        if (user == null || user.getId() == null) {
            throw new RuntimeException("用户未登录");
        }
        //查询用户收藏的帖子id过的记录
        List<Object> objects = redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            StringRedisConnection src = (StringRedisConnection) connection;
            for (Integer postId : postIds) {
                String key = BehaviorConstants.COLLECTION_BEHAVIOR + postId;
                src.sIsMember(key,  String.valueOf(user.getId()));
            }
            return null;
        });
        // 创建从0到集合size的流
        // 遍历每个元素，保留结果为true的角标i
        return IntStream.range(0, objects.size()) // 创建从0到集合size的流
                .filter(i -> (boolean) objects.get(i)) // 遍历每个元素，保留结果为true的角标i
                .mapToObj(postIds::get)
                .collect(Collectors.toSet());// 收集9
    }

}
